<?php

namespace App\Models\College;

use App\Models\BaseModel;
use App\Models\Common\ResourcesModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserBaseInfoModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserIdentityCardModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\HasOneThrough;
use Illuminate\Support\Facades\Cache;
use Kuafu\Snow\KfSnow;

class CollegeTrainingOrderModel extends BaseModel
{
    protected $table = 'college_training_orders';

    protected $fillable = [
        'orderNo',
        'planId',
        'studentShopId',
        'teacherShopId',
        'actualNum',
        'planNum',
        'status',
        'merchantConfirmTime',
        'result',
    ];

    const STATUS_MERCHANT_CONFIRM = 1;
    const STATUS_COLLEGE_CONFIRM  = 2;
    const STATUS_ING              = 3;
    const STATUS_WAIT_UPLOAD      = 4;
    const STATUS_FINISH           = 5;
    const STATUS_CLOSE            = 6;

    const STATUS_TEXT = [
        self::STATUS_MERCHANT_CONFIRM => '商家待确认',
        self::STATUS_COLLEGE_CONFIRM  => '商学院待确认',
        self::STATUS_ING              => '进行中',
        self::STATUS_WAIT_UPLOAD      => '实操待上传',
        self::STATUS_FINISH           => '已完成',
        self::STATUS_CLOSE            => '已关闭',
    ];

    const RESULT_INIT    = 0; // 初始化
    const RESULT_SUCCESS = 1; // 合格
    const RESULT_FAIL    = 2; // 不合格

    public function planRel(): HasOne
    {
        return $this->hasOne(CollegeTrainingPlanModel::class, 'id', 'planId');
    }

    public function userRel(): HasMany
    {
        return $this->hasMany(CollegeTrainingOrderUserModel::class, 'trainingOrderId');
    }

    public function logRel(): HasMany
    {
        return $this->hasMany(CollegeTrainingOrderLogModel::class, 'orderId');
    }

    public function planUserRel(): HasMany
    {
        return $this->hasMany(CollegeTrainingOrderPlanUserModel::class, 'trainingOrderId');
    }

    public static function init(int $shopId)
    {
        return self::query()->create([
            'orderNo'       => "PX" . KfSnow::nextIdCache(),
            'planId'        => 0,
            'studentShopId' => $shopId,
            'actualNum'     => 0,
            'planNum'       => 0,
            'status'        => self::STATUS_MERCHANT_CONFIRM,
        ]);
    }

    /**
     * 获得加盟商姓名
     * @return HasOneThrough
     */
    public function userIdentityRel(): HasOneThrough
    {
        return $this->hasOneThrough(
            OpenShopUserIdentityCardModel::class,
            OpenShopMainProcessModel::class,
            'shopId',
            'orderNo',
            'studentShopId',
            'orderNo'
        );
    }

    /**
     * 获得加盟商基本信息
     * @return HasOneThrough
     */
    public function userBaseInfoRel(): HasOneThrough
    {
        return $this->hasOneThrough(
            OpenShopUserBaseInfoModel::class,
            OpenShopMainProcessModel::class,
            'shopId',
            'orderNo',
            'studentShopId',
            'orderNo'
        );
    }

    public function siteLocationRel(): HasOneThrough
    {
        return $this->hasOneThrough(
            OpenShopSiteLocationModel::class,
            OpenShopMainProcessModel::class,
            'shopId',
            'mainProcessId',
            'studentShopId',
            'id'
        )->where('source', 0)->where('childLocationOrder', 0);
    }

    public function resourceTrainCompleteImgRel(): HasMany
    {
        return $this->hasMany(ResourcesModel::class, 'businessId')
            ->where('module', ResourcesModel::MODULE_TYPE_COLLEGE)
            ->where('business', ResourcesModel::BUSINESS_COLLEGE_COURSES)
            ->whereIn('name', ['trainCompleteImg', 'failLetter']);
    }

    public function resourcePracticeTrainingRel(): HasMany
    {
        return $this->hasMany(ResourcesModel::class, 'businessId')
            ->where('module', ResourcesModel::MODULE_TYPE_COLLEGE)
            ->where('business', ResourcesModel::BUSINESS_COLLEGE_COURSES)
            ->where('name', 'practiceTraining');
    }

    public function resourceFailLetterRel(): HasMany
    {
        return $this->hasMany(ResourcesModel::class, 'businessId')
            ->where('module', ResourcesModel::MODULE_TYPE_COLLEGE)
            ->where('business', ResourcesModel::BUSINESS_COLLEGE_COURSES)
            ->where('name', 'failLetter');
    }

    /**
     * 重置result，变为初始化
     * @return void
     */
    public function resetResult(): void
    {
        // 没有异常的人，改成初始化
        if ($this->result == CollegeTrainingOrderModel::RESULT_FAIL) {
            if ($this->userRel->where('examResult', CollegeTrainingOrderUserModel::RESULT_FAIL)->count() == 0) {
                $this->result = CollegeTrainingOrderModel::RESULT_INIT;
                $this->save();
            }
        }
    }

    /**
     * @return HasOne
     */
    public function openShopMainProcessRel(): HasOne
    {
        return $this->hasOne(OpenShopMainProcessModel::class, "shopId", "studentShopId");
    }
}
